import { createRouter, createWebHistory } from 'vue-router'
import Projects from "../components/Projects.vue"
import Login from "../components/Login.vue"
import User from "../components/User.vue"
import NotFound from "../components/NotFound.vue" // 新增404页面组件

const routes = [{
        path: '/',
        redirect: '/login',
    },
    {
        path: '/projects',
        name: 'Projects',
        component: Projects,
        meta: {
            requiresAuth: true,
            title: '项目管理'
        },
    },
    {
        path: '/login',
        name: 'Login',
        component: Login,
        meta: {
            title: '用户登录',
            guestOnly: true // 仅未登录用户可访问
        }
    },
    {
        path: '/user',
        name: 'User',
        component: User,
        meta: {
            requiresAuth: true,
            title: '用户中心'
        },
    },
    // 动态导入的懒加载路由
    {        
        path: '/projects/new',
        name: 'Requirements',
        component: () =>
            import ('../components/Requirements.vue'),
        meta: {
            requiresAuth: true,
            title: '新建项目'
        },
        pros: true
    },
    {        
        path: '/projects/edit/:id',
        name: 'EditProject',
        component: () =>
            import ('../components/ProjectDetail.vue'),
        meta: {
            requiresAuth: true,
            title: '编辑项目'
        },
        props: true // 将路由参数作为props传递
    },
    {        
        path: '/projects/:id',
        name: 'ProjectDetail',
        component: () =>
            import ('../components/ProjectDetail.vue'),
        meta: {
            requiresAuth: true,
            title: '项目详情'
        },
        props: true // 将路由参数作为props传递
    },
    // 404页面处理
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: NotFound,
        meta: {
            title: '页面不存在'
        }
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes,
    // 自定义滚动行为
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition
        } else {
            return { top: 0 }
        }
    }
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('token')
    const isAuthenticated = !!token

    // 设置页面标题
    document.title = to.meta.title || '皮革产品打样需求管理系统'

    // 检查路由是否需要认证
    if (to.meta.requiresAuth && !isAuthenticated) {
        // 重定向到登录页，并携带原路径
        next({
            name: 'Login',
            query: { redirect: to.fullPath }
        })
        return
    }

    // 检查是否只允许未登录用户访问（如登录页）
    if (to.meta.guestOnly && isAuthenticated) {
        next({ name: 'Projects' }) // 已登录用户跳转到首页
        return
    }

    // 其他情况正常放行
    next()
})

// 全局后置钩子
router.afterEach((to, from) => {
    // 可以在这里添加页面访问统计等逻辑
})

// 全局错误处理
router.onError((error) => {
    console.error('路由错误:', error)
        // 可以跳转到错误页面
    router.push({ name: 'NotFound' })
})

export default router